package controller

import (
	"errors"
	"ginfast/api/weixin/internal"
	"ginfast/api/weixin/service"
	"ginfast/pkg/ginx"
	"net/http"

	"github.com/gin-gonic/gin"
)

type WeChat struct {
}

type advanced struct {
	Signature string `form:"signature" binding:"required"`
	Timestamp string `form:"timestamp" binding:"required"`
	Nonce     string `form:"nonce" binding:"required"`
	Echostr   string `form:"echostr" binding:"required"`
}

// AdvancedHandler token接口
func (WeChat) AdvancedHandler(c *gin.Context) {
	var p advanced
	//获取参数
	ctx, err := ginx.MustBind(c, &p)
	if err != nil {
		return
	}
	opt, err := service.OfficailConfig()
	if err != nil {
		ctx.WriteError(err)
		return
	}
	if ok := internal.Signature(p.Signature, p.Timestamp, p.Nonce, opt.Token); !ok {
		ctx.WriteError(errors.New("Signature"))
		return
	}
	c.String(http.StatusOK, p.Echostr)
}

type minilogin struct {
	JSCode string `form:"jsCode" binding:"required,min=5,max=64"`
}

// UserLoginHandler 登录
func (WeChat) UserLoginHandler(c *gin.Context) {
	// appId := c.GetHeader("appId")
	// thirdSession := c.GetHeader("thirdSession")
	var p minilogin
	ctx, err := ginx.MustBind(c, &p)
	if err != nil {
		return
	}
	data, err := internal.Auth.Code2Session(p.JSCode)
	ctx.WriteData(gin.H{"data": data, "sessionKey": data.Sessionkey}, err)
}

// OfficeMsgHandler 消息处理
func (WeChat) OfficialMsgHandler(c *gin.Context) {
	OfficialMsgHandler(c)
}

func (o WeChat) Routers(r *gin.RouterGroup) {
	r.GET("", o.AdvancedHandler)
	r.POST("", o.OfficialMsgHandler)
	r.POST("/login", o.UserLoginHandler)
}
